﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;



public class GameController : MonoBehaviour
{
    public static GameController instance;
    public List<GameObject> path;
    public List<GameObject> path2;
    public List<GameObject> allPrefabs;
    public List<GameObject> allBoxs;
    public List<Transform> itemPositions;
    public GameObject currentBox;
    public GameObject pathParent, path2Parent, boxPlatform;
    public bool hasBox = false;
    int currentBoxSize = 0;
    public int comidySize = 0;
    public bool comidyFragile;
    public bool comidyLeak;
    public bool isBoxBag, isBoxPlatform;
    public GameObject say;
    public GameObject renwu;
    public Material light01, light02;
    public GameObject glow01, glow02;

    private void Awake()
    {
        //v = new SpVoice();
        //v.Speak("", SpeechVoiceSpeakFlags.SVSFlagsAsync);
        instance = this;
        for (int i = 0; i < pathParent.transform.childCount; i++)
            path.Add(pathParent.transform.GetChild(i).gameObject);
        for (int i = 0; i < path2Parent.transform.childCount; i++)
            path2.Add(path2Parent.transform.GetChild(i).gameObject);
    }

    public void StartGame()
    {
        if (currentBox)
            Destroy(currentBox);
        var list = GameObject.FindGameObjectsWithTag("items");
        for (int i = 0; i < list.Length; i++)
            Destroy(list[i]);
        if (LvController.Instance.currentLv >= 7)
            StartCoroutine(IECreateBox());
        else
        {
            //var list = GameObject.FindGameObjectsWithTag("items");
            //for (int i = 0; i < list.Length; i++)
            //    Destroy(list[i]);
            //for (int i = 0; i < 3; i++)
                CreateBoxAtPosition(0);
        }
        CreateBox();
    }

    public void EndGame()
    {
        StopAllCoroutines();
        hasBox = false;
    }

    public void CreateBoxAtPosition(int index)
    {
        var list = GameObject.FindGameObjectsWithTag("items");
        for (int i = 0; i < list.Length; i++)
            Destroy(list[i]);
        for (int i = 0; i < 3; i++)
        {
            GameObject go = Instantiate(Resources.Load(GetItemName())) as GameObject;
            float scaleTo = go.transform.localScale.x;
            go.transform.localScale = Vector3.zero;
            go.transform.position = itemPositions[i].position;
            go.GetComponent<Comidy>().Init(false, i);
            go.transform.DOScale(scaleTo, 0.35f).SetEase(Ease.OutBack);
            go.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, 0));
        }
    }

    IEnumerator IECreateBox()
    {
        while (true)
        {
            GameObject go = Instantiate(Resources.Load(GetItemName())) as GameObject;
            go.transform.position = path[0].transform.position;
            go.GetComponent<Comidy>().Init(true);
            yield return new WaitForSeconds(1.8f);
        }
    }

    string GetItemName()
    {
        int lvIndex = 12;
        if (LvController.Instance.currentLv <= 11)
            lvIndex = LvController.Instance.currentLv;
        List<int> itemNum = LvController.Instance.itemDic[lvIndex];
        int itemID = itemNum[Random.Range(0, itemNum.Count)];
        return LvController.Instance.itemNames[itemID];
    }

    string finalBoxBoomOrFlatten = "";
    string finalDamp = "";
    string finalSize = "";
    int Check()
    {
        switch (currentBoxSize)
        {
            case 0:
                finalSize = "_small";
                break;
            case 1:
                finalSize = "_middle";
                break;
            case 2:
                finalSize = "_big";
                break;
            default:
                finalSize = "_middle";
                break;
        }
        if (comidySize > currentBoxSize)
        {
            finalBoxBoomOrFlatten = "_Boom";
            return 1;
        }
        else if (comidySize < currentBoxSize)
        {
            finalBoxBoomOrFlatten = "_Flatten";
            return 2;
        }
        else if (comidyFragile && !isBoxPlatform)
        {
            return 3;
        }
        else if (comidyLeak && !isBoxBag)
        {
            finalDamp = "_Damp";
            return 4;
        }
        else
            return 0;
    }

    void CreateBox()
    {
        isBoxPlatform = false;
        isBoxBag = false;
        finalBoxBoomOrFlatten = "";
        finalDamp = "";
        finalSize = "";
        if (LvController.Instance.currentLv <= 2)
            currentBoxSize = 2;
        else if (LvController.Instance.currentLv == 3 || LvController.Instance.currentLv == 5)
            currentBoxSize = Random.Range(1, 3);
        else if (LvController.Instance.currentLv == 4)
            currentBoxSize = 1;
        else if(LvController.Instance.currentLv == 7)
            currentBoxSize = Random.Range(0, 2);
        else
            currentBoxSize = Random.Range(0, 3);
        switch (currentBoxSize)
        {
            case 0:
                currentBox = Instantiate(Resources.Load("Box_start_small_01")) as GameObject;
                break;
            case 1:
                currentBox = Instantiate(Resources.Load("Box_start_middle_01")) as GameObject;
                break;
            case 2:
                currentBox = Instantiate(Resources.Load("Box_start_big_01")) as GameObject;
                break;
        }
        currentBox.transform.position = boxPlatform.transform.position + new Vector3(0, 10, 0);
        Sequence s = DOTween.Sequence();
        s.Append(currentBox.transform.DOMoveY(0.735f, 1f).SetEase(Ease.InExpo))
            //.Append(currentBox.transform.DOScale(new Vector3(1.2f, 0.8f, 1.2f), 0.1f))
            //.Append(currentBox.transform.DOScale(Vector3.one, 0.1f))
            .OnComplete(() => { this.hasBox = true; });
    }

    public void MoveBox(GameObject go)
    {
        this.hasBox = false;
        StartCoroutine(IEMoveBox(go));
    }

    IEnumerator IEMoveBox(GameObject commidy)
    {
        GameObject go = null;
        Sequence s = DOTween.Sequence();
        s.Append(currentBox.transform.DOMoveZ(0.6f, 1f)).OnComplete(() =>
            {
                int checkResult = Check();
                string finalname = "Box_end" + finalBoxBoomOrFlatten + finalDamp + finalSize;
                go = Instantiate(Resources.Load(finalname)) as GameObject;

                if (checkResult == 1)
                {
                    GameObject item = commidy;
                    item.transform.SetParent(go.transform);
                    item.transform.localPosition = Vector3.zero;
                }
                Destroy(currentBox);

                go.transform.position = path2[0].transform.position;
                Vector3[] vecPath = new Vector3[path2.Count];
                for (int i = 0; i < path2.Count; i++)
                    vecPath[i] = path2[i].transform.position;
                Tweener dt = go.transform.DOPath(vecPath, 4, PathType.CatmullRom, PathMode.Full3D, 15).SetLookAt(0).SetEase(Ease.Linear);
                dt.OnComplete(() => Destroy(go));
                say.SetActive(true);
                say.transform.GetChild(0).gameObject.SetActive(true);
                for (int i = 1; i < say.transform.childCount; i++)
                    say.transform.GetChild(i).gameObject.SetActive(i == checkResult + 1);
                if (checkResult == 0)
                {
                    Sequence q = DOTween.Sequence();
                    q.Append(light01.DOColor(Color.green, 0.1f)).AppendInterval(2f).Append(light01.DOColor(new Color(0.3f, 0.3f, 0.3f), 0.1f));
                    Sequence q1 = DOTween.Sequence();
                    q1.Append(glow01.transform.DOScale(1, 0.1f)).AppendInterval(1.9f).Append(glow01.transform.DOScale(0, 0.1f));
                    renwu.GetComponent<Animation>().Play("XGG_happy");
                    renwu.transform.Find("XGG").GetComponent<Renderer>().materials[1].CopyPropertiesFromMaterial(Resources.Load("face_happy") as Material);
                    LvController.Instance.AddPerfect(true);
                }
                else
                {
                    Sequence q = DOTween.Sequence();
                    q.Append(light02.DOColor(Color.white, 0.1f)).AppendInterval(2f).Append(light02.DOColor(Color.black, 0.1f));
                    Sequence q1 = DOTween.Sequence();
                    q1.Append(glow02.transform.DOScale(1, 0.1f)).AppendInterval(1.9f).Append(glow02.transform.DOScale(0, 0.1f));
                    renwu.GetComponent<Animation>().Play("XGG_bad");
                    renwu.transform.Find("XGG").GetComponent<Renderer>().materials[1].CopyPropertiesFromMaterial(Resources.Load("face_bad") as Material);
                    LvController.Instance.AddPerfect(false);
                }
            });
        yield return new WaitForSeconds(3);
        for (int i = 0; i < 2; i++)
            say.transform.GetChild(i).gameObject.SetActive(false);
        say.SetActive(false);
        renwu.GetComponent<Animation>().Play("XGG_standby");
        renwu.transform.Find("XGG").GetComponent<Renderer>().materials[1].CopyPropertiesFromMaterial(Resources.Load("face_standby") as Material);
        CreateBox();
    }
}